# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
import math
from src.model import InvRescaleNet
import mindspore.nn as nn
from mindspore import ops
from mindspore.common import initializer as init
from mindspore import Tensor
import mindspore as ms
from mindspore.ops import composite as C
from mindspore.ops import functional as F


#########################################################################
#                            define_network
#########################################################################
def define_G(args):
    down_num = int(math.log(args.G_scale, 2))
    net = InvRescaleNet(args.in_nc, args.out_nc, subnet(args.G_init), args.block_num, down_num)
    return net


#########################################################################
#                            init_weights
#########################################################################
def init_weights(net, init_type='xavier', init_gain=0.1):
    """
    Initialize network weights.
    Parameters:
        net (Cell): Network to be initialized
        init_type (str): The name of an initialization method: normal | xavier.
        init_gain (float): Gain factor for normal and xavier.
    """
    for _, cell in net.cells_and_names():
        if isinstance(cell, (nn.Conv2d, nn.Conv2dTranspose)):
            if init_type == 'normal':
                cell.weight.set_data(init.initializer(init.Normal(init_gain), cell.weight.shape))
            elif init_type == 'xavier':
                cell.weight.set_data(init.initializer(init.XavierUniform(init_gain), cell.weight.shape))
            elif init_type == 'constant':
                cell.weight.set_data(init.initializer(0.001, cell.weight.shape))
            else:
                raise NotImplementedError('initialization method [%s] is not implemented' % init_type)
        elif isinstance(cell, (nn.BatchNorm2d, nn.InstanceNorm2d)):
            cell.gamma.set_data(init.initializer('ones', cell.gamma.shape))
            cell.beta.set_data(init.initializer('zeros', cell.beta.shape))


def subnet(init='xavier'):
    def constructor(channel_in, channel_out):
        if init == 'xavier':
            net = DenseBlock(channel_in, channel_out)
            init_weights(net, init_type='xavier', init_gain=0.1)
            return net
        else:
            return DenseBlock(channel_in, channel_out)

    return constructor


#########################################################################
#                            Basic block
#########################################################################
class DenseBlock(nn.Cell):
    """
    DenseBlock definition.

    Args:
        channel_in: input channels.
        channel_out: output channels.
        init: the method of init-weight.Default:'xavier'.
        gc: the growth of channels.
        bias: whether use bias or not.
    """

    def __init__(self, channel_in, channel_out, gc=32, bias=True):
        super(DenseBlock, self).__init__()
        self.conv1 = nn.Conv2d(channel_in, gc, 3, 1, pad_mode="pad", padding=1, has_bias=bias)
        self.conv2 = nn.Conv2d(channel_in + gc, gc, 3, 1, pad_mode="pad", padding=1, has_bias=bias)
        self.conv3 = nn.Conv2d(channel_in + 2 * gc, gc, 3, 1, pad_mode="pad", padding=1, has_bias=bias)
        self.conv4 = nn.Conv2d(channel_in + 3 * gc, gc, 3, 1, pad_mode="pad", padding=1, has_bias=bias)
        self.conv5 = nn.Conv2d(channel_in + 4 * gc, channel_out, 3, 1, pad_mode="pad", padding=1, has_bias=bias)
        self.lrelu = nn.LeakyReLU(alpha=0.2)
        self.concat = ops.Concat(1)

    def construct(self, x):
        x1 = self.lrelu(self.conv1(x))
        x2 = self.lrelu(self.conv2(self.concat((x, x1))))
        x3 = self.lrelu(self.conv3(self.concat((x, x1, x2))))
        x4 = self.lrelu(self.conv4(self.concat((x, x1, x2, x3))))
        x5 = self.conv5(self.concat((x, x1, x2, x3, x4)))
        return x5


#########################################################################
#                            Utils
#########################################################################
class Rounding(nn.Cell):
    """the rounding operation"""
    def __init__(self):
        super(Rounding, self).__init__()
        self.round = ops.Round()
        self.min = Tensor(0, ms.float32)
        self.max = Tensor(1, ms.float32)

    def construct(self, x):
        x = C.clip_by_value(x, self.min, self.max)
        x = self.round(x * 255.) / 255.
        return x


class Quantization(nn.Cell):
    """the quantization operation"""
    def __init__(self):
        super(Quantization, self).__init__()
        self.rounding = Rounding()

    def construct(self, x):
        x1 = F.stop_gradient(x)
        rounded = self.rounding(x1)
        residual = rounded - x1
        return x + residual



